#include "Utils.h"

string Utils::ftoa(float f)
{
	char str[20] = "";
	sprintf(str, "%f", f);
	string t = str;
	return t;
}

int Utils::atoi(const char* str_int) {
	int i;
	if(EOF == sscanf(str_int, "%d", &i))
	{
		//error
	}
	return i;
}

int Utils::SplitString(const string& input, 
       const string& delimiter, vector<string>& results, 
       bool includeEmpties)
{
    int iPos = 0;
    int newPos = -1;
    int sizeS2 = (int)delimiter.size();
    int isize = (int)input.size();

    if( 
        ( isize == 0 )
        ||
        ( sizeS2 == 0 )
    )
    {
        return 0;
    }

    vector<int> positions;

    newPos = input.find (delimiter, 0);

    if( newPos < 0 )
    { 
        return 0; 
    }

    int numFound = 0;

    while( newPos >= iPos )
    {
        numFound++;
        positions.push_back(newPos);
        iPos = newPos;
        newPos = input.find (delimiter, iPos+sizeS2);
    }

    if( numFound == 0 )
    {
        return 0;
    }

    for( int i=0; i <= (int)positions.size(); ++i )
    {
        string s("");
		int offset = 0;
        if( i == 0 ) 
        { 
            s = input.substr( i, positions[i] ); 
		}else {
			offset = positions[i-1] + sizeS2;
		}
        if( offset < isize )
        {
            if( i == positions.size() )
            {
                s = input.substr(offset);
            }
            else if( i > 0 )
            {
                s = input.substr( positions[i-1] + sizeS2, 
                      positions[i] - positions[i-1] - sizeS2 );
            }
        }
        if( includeEmpties || ( s.size() > 0 ) )
        {
            results.push_back(s);
        }
    }
    return numFound;
}

string Utils::getLocalIP() {

	//taken from http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c2487/
	//with small modifications.
	//article by Jeff Lundgren
	//February 9, 1999
	
	WORD wVersionRequested;
	WSADATA wsaData;
	char name[255];
	string ip;
	PHOSTENT hostinfo;
	wVersionRequested = MAKEWORD( 2, 0 );

	if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
	{

		if( gethostname ( name, sizeof(name)) == 0)
		{
			if((hostinfo = gethostbyname(name)) != NULL)
			{
				ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
			}
		}

		WSACleanup( );
	}
	return ip;
}